package com.ttt.service;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class AiService
{
    private String aiUrl="https://spark-api-open.xf-yun.com/v2/chat/completions";
    private String aiApiPassword="Bearer HFfGZzphySzIgnphdHFq:btiTvoKiLzXXkBLjLSTx";
    private String aiHeader="Content-Type: application/json";
    /**
     * 交互方法
     */
    public String getAiResponse(String text) throws IOException {
        String aiRequestText="{\n" +
                "    \"model\": \"x1\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \""+text+"\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        HttpPost httpPost=new HttpPost(aiUrl);
        httpPost.setHeader("Authorization",aiApiPassword);
        httpPost.setHeader("Content-Type",aiHeader);
        httpPost.setEntity(new StringEntity(aiRequestText,"UTF-8"));
        // TODO 发送请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse httpResponse=httpClient.execute(httpPost);
        // TODO 判断响应状态
        if(httpResponse.getStatusLine().getStatusCode()==200){
            // TODO 获取数据
            System.out.println(httpResponse.getEntity().toString()+"<===>");
            return EntityUtils.toString(httpResponse.getEntity(),"UTF-8");
        }else {
            return String.valueOf(httpResponse.getStatusLine().getStatusCode());
        }

    }
}
